package com.example.demo.component.docker;

import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName docker_client_factory
 * @Description
 * @date 2022/11/7 11:07
 * @Author yanceysong
 * @Version 1.0
 */
public class docker_client_factory {
    private static final ConcurrentHashMap<String, docker_client> docker_client_pool = new ConcurrentHashMap<>();

    /**
     * 根据ip获取对应的docker连接
     *
     * @param ip   docker坐在的地址
     * @param port 对外开放的端口号
     * @return docker连接
     */
    public static docker_client get_docker_client(String ip, String port) {
        if (!docker_client_pool.contains(ip)) {
            docker_client_pool.put(ip, new docker_client(ip, port));
        }
        return docker_client_pool.get(ip);
    }
    /**
     * 根据ip获取对应的docker连接
     *
     * @param ip   docker坐在的地址
     * @return docker连接
     */
    public static docker_client get_docker_client(String ip) {
        if (!docker_client_pool.contains(ip)) {
            docker_client_pool.put(ip, new docker_client(ip, "2375"));
        }
        return docker_client_pool.get(ip);
    }

    /**
     * 关闭所有连接工厂内的所有docker连接
     */
    public static void close_all() {
        Iterator<String> iterator = docker_client_pool.keySet().stream().iterator();
        while (iterator.hasNext()) {
            docker_client_pool.get(iterator.next()).close();
        }
    }

    /**
     * 关闭单个连接
     *
     * @param ip ip
     */
    public static void close(String ip) {
        //注意:傻逼ConcurrentHashMap默认contains是containsValue，判断key是否存在需要使用containsKey
        if (docker_client_pool.containsKey(ip))
            docker_client_pool.get(ip).close();
    }
}
